#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "saveconfirmdialog.h"
#include "syntaxhighlighter.h"
#include "shortcutconfigdialog.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    ,ui(new Ui::MainWindow)
    ,findDialog(new FindReplaceDialog(this))
{
    ui->setupUi(this);
    setWindowTitle("记事本");
    currentFile.clear();

    //查找替换
    connect(findDialog, &FindReplaceDialog::findRequested, this, &MainWindow::findText);
    connect(findDialog, &FindReplaceDialog::replaceRequested, this, &MainWindow::replaceText);
    connect(findDialog, &FindReplaceDialog::replaceAllRequested, this, &MainWindow::replaceAllText);
    // 确保初始光标位置正确
    ui->textEdit->moveCursor(QTextCursor::Start);

    // 全屏化textEdit
    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(centralWidget);
    layout->addWidget(ui->textEdit);
    layout->setContentsMargins(0, 0, 0, 0);
    setCentralWidget(centralWidget);

    initStatusBar();

    // 自动保存设置（每5分钟保存一次）
    autoSaveTimer = new QTimer(this);
    connect(autoSaveTimer, &QTimer::timeout, this, &MainWindow::autoSave);
    autoSaveTimer->start(5 * 60 * 1000); // 5分钟

    // 启动时检查恢复文件
    QTimer::singleShot(1000, this, &MainWindow::loadAutoSave);


    highlighter = new CppHighlighter(ui->textEdit->document());



    // 初始化快捷键系统
    setupShortcutActions();
    loadShortcuts();

}
void MainWindow::setupShortcutActions() {
    // 注册所有可配置的action
    shortcutActions = {
        {"file.new", ui->actionNew},
        {"file.open", ui->actionOpen},
        {"file.save", ui->actionSave},
        {"file.save_as", ui->actionSaveAs},
        {"edit.undo", ui->undoAction},
        {"edit.redo", ui->redoAction},
        {"edit.cut", ui->cutAction},
        {"edit.copy", ui->copyAction},
        {"edit.paste", ui->pasteAction},
        {"edit.find", ui->findAction},
        {"edit.replace", ui->replaceAction}
    };

    // 确保Qt Designer中所有action的shortcut属性为空
    for (auto action : shortcutActions) {
        action->setShortcut(QKeySequence());
    }
}



void MainWindow::applyShortcuts(const QHash<QString, QKeySequence>& shortcuts) {
    for (auto it = shortcuts.begin(); it != shortcuts.end(); ++it) {
        if (shortcutActions.contains(it.key())) {
            shortcutActions[it.key()]->setShortcut(it.value());
        }
    }
}

void MainWindow::loadShortcuts() {
    QSettings settings;
    settings.beginGroup("Shortcuts");

    for (auto it = shortcutActions.begin(); it != shortcutActions.end(); ++it) {
        QKeySequence shortcut = settings.value(it.key(), QKeySequence()).value<QKeySequence>();
        if (!shortcut.isEmpty()) {
            it.value()->setShortcut(shortcut);
        }
    }

    settings.endGroup();
}

void MainWindow::saveShortcuts() {
    QSettings settings;
    settings.beginGroup("Shortcuts");

    for (auto it = shortcutActions.begin(); it != shortcutActions.end(); ++it) {
        settings.setValue(it.key(), it.value()->shortcut());
    }

    settings.endGroup();
}


QString MainWindow::autoSavePath() {
    return QStandardPaths::writableLocation(QStandardPaths::TempLocation)
    + "/notepad_autosave_"
        + QFileInfo(QCoreApplication::applicationFilePath()).fileName()
        + ".tmp";
}

void MainWindow::autoSave() {
    if (!ui->textEdit->document()->isModified())
        return;

    QFile file(autoSavePath());
    if (file.open(QIODevice::WriteOnly)) {
        QTextStream out(&file);
        out << ui->textEdit->toPlainText();
        file.close();

        // 调试用
        qDebug() << "自动保存到:" << autoSavePath()
                 << "时间:" << QDateTime::currentDateTime().toString();
    }
}


void MainWindow::myCloseEvent(QCloseEvent *event) {
    if (maybeSave()) {  // 你的原有保存检查函数
        // 删除自动保存文件
        QFile::remove(autoSavePath());
        qDebug()<<"执行删除";
        event->accept();
    } else {
        event->ignore();
    }
}


//恢复
void MainWindow::loadAutoSave() {
    QString path = autoSavePath();
    if (QFile::exists(path)) {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "恢复文件",
                                      "检测到未保存的编辑内容，是否恢复？",
                                      QMessageBox::Yes|QMessageBox::No);

        if (reply == QMessageBox::Yes) {
            QFile file(path);
            if (file.open(QIODevice::ReadOnly)) {
                ui->textEdit->setPlainText(file.readAll());
                ui->textEdit->document()->setModified(true);
                file.close();
            }
        }

        // 无论是否恢复都删除临时文件
        QFile::remove(path);
    }
}



MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::initAbout(){

        // 初始化关于对话框（延迟创建）
    aboutDialog = new AboutDialog(this);
    aboutDialog->setAppInfo(
        tr("记事本"),
        "1.0.0",
        tr("版权所有 © 2025 天津大学")
        );

}



void MainWindow::initStatusBar(){
    // 创建状态栏标签
    positionLabel = new QLabel(this);
    encodingLabel = new QLabel("UTF-8", this);  // 默认编码
    // 添加样式
    positionLabel->setStyleSheet("QLabel { color: #555; font-weight: bold; padding-left: 5px;}");
    encodingLabel->setStyleSheet("QLabel { color: #777; padding-right: 5px;}");
    //状态栏
    ui->statusBar->addPermanentWidget(positionLabel);
    ui->statusBar->setStyleSheet("QStatusBar::item { border: none; }");
    ui->statusBar->addPermanentWidget(new QLabel("|", this));  // 分隔线
    ui->statusBar->addPermanentWidget(encodingLabel);

    // 连接光标位置变化信号
    connect(ui->textEdit, &QTextEdit::cursorPositionChanged,
            this, &MainWindow::updateStatusBar);
    // 初始更新
    updateStatusBar();

}





// 新建文件
void MainWindow::on_actionNew_triggered() {
    if (maybeSave()) { // 检查是否需要保存当前文件
        if (!ui->textEdit->document()->isModified() || 
            (currentFile.isEmpty() && on_actionSave_triggered())) {
            ui->textEdit->clear();
            currentFile.clear();
             highlighter->setDocument(nullptr); // 禁用高亮
        }
    }
}

// 打开文件
void MainWindow::on_actionOpen_triggered() {
        QString documentPath= QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
        QString fileName = QFileDialog::getOpenFileName(this, "打开文件",documentPath, "文本文件 (*.txt)");
        if (!fileName.isEmpty()) {
            loadFile(fileName);
        }
}

// 保存文件
bool MainWindow::on_actionSave_triggered() {
    if (currentFile.isEmpty()) {    // 若当前文件名为空，则执行另存为
        return on_actionSaveAs_triggered();    //
    } else {
        saveFile(currentFile);
        return true;
    }
}

// 另存为
bool  MainWindow::on_actionSaveAs_triggered() {
    QString fileName = QFileDialog::getSaveFileName(this, "另存为", "", "文本文件 (*.txt)");
    if (!fileName.isEmpty()) {
        saveFile(fileName);
        return true;
    }
    return false;
}


// 辅助函数：加载文件内容
void MainWindow::loadFile(const QString &fileName) {
    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        ui->textEdit->setText(in.readAll());
        currentFile = fileName;
        file.close();

        setWindowTitle(QFileInfo(fileName).fileName()+"-记事本");



        // 如果是C++文件则启用高亮
        if (fileName.endsWith(".cpp") || fileName.endsWith(".h")) {
            highlighter->setDocument(ui->textEdit->document());
        } else {
            highlighter->setDocument(nullptr); // 禁用高亮
        }
    }
}

// 辅助函数：保存文件
void MainWindow::saveFile(const QString &fileName) {
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        out << ui->textEdit->toPlainText();
        currentFile = fileName;
        file.close();

        setWindowTitle(QFileInfo(fileName).fileName()+"    -记事本");
    }

}

// 检查是否需要保存
bool MainWindow::maybeSave() {
    if (ui->textEdit->document()->isModified()) {
      SaveConfirmDialog diglog(this);
      int result =diglog.exec();
      switch (result){
      case SaveConfirmDialog::Save:
         return  on_actionSave_triggered();//save
      case SaveConfirmDialog::Discard:
          return true; //discard
      case SaveConfirmDialog::Cancel:
          return false; //cancel    
      }
    }
    return true;  // 文件未修改或用户选择丢弃
}




void MainWindow::on_selectAllAction_triggered()
{
    ui->textEdit->selectAll();
}

void MainWindow::on_pasteAction_triggered()
{
    ui->textEdit->paste();
}

void MainWindow::on_copyAction_triggered()
{
    ui->textEdit->copy();
}

void MainWindow::on_cutAction_triggered()
{
    ui->textEdit->cut();
}

void MainWindow::on_redoAction_triggered()
{
    ui->textEdit->redo();
}

void MainWindow::on_undoAction_triggered()
{
    ui->textEdit->undo();
}

void MainWindow::on_deleteAction_triggered()
{

   }

void MainWindow::on_fontAction_triggered()
{
    bool ok;
    QFont font = QFontDialog::getFont(&ok, ui->textEdit->font(), this,"字体");
       if (ok) {
           ui->textEdit->setFont(font);
       }
}

void MainWindow::on_colorAction_triggered()
{
    QColor color =
            QColorDialog::getColor(ui->textEdit->colorCount(),this,"字体颜色");
    if(color.isValid()){
        ui->textEdit->setTextColor(color);// set color


        QPalette pal=ui->textEdit->palette();//set pal at the same time
        pal.setColor(QPalette::HighlightedText,color);
        ui->textEdit->setPalette(pal);
    }

}

void MainWindow::on_findAction_triggered()
{
    findDialog->show();
    positionFindDialog();
    findDialog->setCurrentTab(0); // 切换到查找页
     findDialog->activateWindow();
}

void MainWindow::on_replaceAction_triggered()
{
    findDialog->show();
    positionFindDialog();
      findDialog->setCurrentTab(1); // 切换到替换页
       findDialog->activateWindow();
}


void MainWindow::findText(const QString &text, QTextDocument::FindFlags flags) {
    if(text.isEmpty()){

        QPoint dialogPos = findDialog->mapToGlobal(QPoint(0,0));

        QPoint tooltipPos = dialogPos + QPoint(findDialog->width()/2, findDialog->height()-20 );


        QToolTip::showText(tooltipPos,
                          "<span style='color:red; font-weight:bold'>请输入查找内容</span>",
                          findDialog);
        return;
}

     QTextCursor cursor = ui->textEdit->textCursor();
     bool found =ui->textEdit->find(text, flags);
     if(!found){
         cursor.movePosition(QTextCursor::Start);//移动到开头
         ui->textEdit->setTextCursor(cursor);

         found=ui->textEdit->find(text, flags);

     }






    if (!found) {

        QMessageBox::information(this, "记事本", "找不到 \"" + text + "\"");
    }





}

void MainWindow::replaceText(const QString &find, const QString &replace, QTextDocument::FindFlags flags) {
    if (ui->textEdit->textCursor().hasSelection() &&
        ui->textEdit->textCursor().selectedText() == find) {
        ui->textEdit->textCursor().insertText(replace);
    }
    findText(find, flags);
}

void MainWindow::replaceAllText(const QString &find, const QString &replace, QTextDocument::FindFlags flags) {
    int count = 0;
    ui->textEdit->moveCursor(QTextCursor::Start);
    while (ui->textEdit->find(find, flags)) {
        ui->textEdit->textCursor().insertText(replace);
        count++;
    }
    QMessageBox::information(this, "记事本", QString("已替换 %1 处").arg(count));
}




void MainWindow::positionFindDialog() {
    if (!findDialog) {

        return;
    }

    // 计算右上角坐标
    QPoint dialogPos = this->geometry().topRight();
    dialogPos -= QPoint(findDialog->width()+30, -40); // 左移对话框宽度

    // 确保不超出屏幕
    QScreen *screen = QGuiApplication::screenAt(this->pos());
    QRect screenGeo = screen ? screen->geometry() : QGuiApplication::primaryScreen()->geometry();

    if (dialogPos.x() < screenGeo.left()) {
        dialogPos.setX(screenGeo.left());
    }

    findDialog->move(dialogPos);
}






void MainWindow::updateStatusBar()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    // 计算行号 (从1开始)
    int line = cursor.blockNumber() + 1;
    // 计算列号 (从1开始)
    int col = cursor.columnNumber() + 1;
    // 更新位置标签
    positionLabel->setText(QString("行: %1, 列: %2").arg(line).arg(col));
    // 设置最小宽度防止闪烁
    positionLabel->setMinimumWidth(120);
    encodingLabel->setMinimumWidth(80);
}



void MainWindow::on_aboutAction_triggered()
{
    if (!aboutDialog) {
        aboutDialog = new AboutDialog(this);
        aboutDialog->setAppInfo(
            tr("记事本"),
            "1.0.0",
            tr("版权所有 © 2025 天津大学")
            );
    }

    aboutDialog->show();
    aboutDialog->raise();
    aboutDialog->activateWindow();
}


void MainWindow::on_shortcutConfigAction_triggered()
{
    ShortcutConfigDialog dialog(shortcutActions, this);
    if (dialog.exec() == QDialog::Accepted) {
        applyShortcuts(dialog.getShortcuts());
        saveShortcuts();
    }
}

